package com.xingfei.blog.utils;

import com.alibaba.fastjson.JSONObject;
import com.xingfei.blog.constants.GeneralConstants;
import com.xingfei.blog.constants.RedisConstants;
import com.xingfei.blog.vo.TokenCode;
import org.apache.commons.lang3.StringUtils;

import java.text.MessageFormat;
/**
* Created with IntelliJ IDEA.
*
* @author: chenxingfei
* @time: 2017/3/22  17:35
* To change this template use File | Settings | File Templates.
*/
public class TokenCodeUtil {

	/**
	 * 生成tokenCode
	 * @param token
	 */
	public static String setTokenCode(String userId){
		String tokenCode = null;
		TokenCode token = new TokenCode();
		token.setUserId(userId);
		if(StringUtils.isNotBlank(token.getUserId())){
			String key = MessageFormat.format(RedisConstants.USER_TOKEN_CODE_KEY, token.getUserId());
			//token码
			String value = JSONObject.toJSONString(token);
			try {
				tokenCode = DESUtil.encryption(value, GeneralConstants.DES_DECODE_KEY);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return tokenCode;
	}

	/**
	 * 获取tokenCode
	 * @param tokenCode
	 */
	public static TokenCode getTokenCode(String tokenCode){
		TokenCode token = null;
		if(tokenCode!=null){
			String jsonStr = null;
			try {
				jsonStr = DESUtil.decryption(tokenCode, GeneralConstants.DES_DECODE_KEY);
			} catch (Exception e) {
				e.printStackTrace();
			}
			token = JSONObject.parseObject(jsonStr, TokenCode.class);
		}
		return token;
	}
}
